#include <memory>
#include "bitmap.h"

namespace herm{
namespace Private{

Bitmap::Bitmap()
{
    m_bits = nullptr;
    m_size = 0;
}

void Bitmap::Init(size_t size)
{	
    m_bits = new Ty[size / sizeof(Ty)];
    m_size = size;
    // construct with all false values
    m_words = (int)(m_size - 1) / Bitsperword;

    Tidy();
}

bool Bitmap::Set(size_t pos)
{	
    if (m_size <= pos)
        return false;

    m_bits[pos / Bitsperword] |= (Ty)1 << pos % Bitsperword;

    return true;
}

bool Bitmap::Reset(size_t pos)
{	
    if (m_size <= pos)
        return false;

    m_bits[pos / Bitsperword] &= ~((Ty)1 << pos % Bitsperword);

    return true;
}

bool Bitmap::Test(size_t pos) const
{	
    if (m_size <= pos)
        return false;

    return ((m_bits[pos / Bitsperword] & ((Ty)1 << pos % Bitsperword)) != 0);
}

void Bitmap::Tidy(Ty val)
{	// Set all words to val
    for (int wpos = m_words; 0 <= wpos; --wpos)
        m_bits[wpos] = val;
    if (val != 0)
        Trim();
}

void Bitmap::Trim()
{	// clear any trailing bits in last word
    if (m_size % Bitsperword != 0)
        m_bits[m_words] &= ((Ty)1 << m_size % Bitsperword) - 1;
}

}
}
